package com.woniuxy.interceptor;



import cn.hutool.json.JSONArray;
import com.woniuxy.conmon.Assert;
import com.woniuxy.conmon.enums.BusinessCode;
import com.woniuxy.interfaces.RequiresPermission;
import com.woniuxy.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 用户权限拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    private static final Map<String, String> URL_PERMISSION_MAP = new HashMap<>();
    static {
        URL_PERMISSION_MAP.put("/user/add", "user:add");
        URL_PERMISSION_MAP.put("/user/list", "user:list");
    }

    /**
     * 前置通知
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("访问资源：{}", request.getRequestURI());
        //判断是否是options请求，如果是则直接放行
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }
        //获取请求头
        String token = request.getHeader("Authorization");

        //判断token是否存在
        Assert.error(Objects.isNull(token), BusinessCode.TOKEN_NOT_EXISTS);

        //验证token是否有效
        Assert.error(!jwtUtil.validateToken(token), BusinessCode.INVALID_TOKEN);

        //判断IP地址是否相同
        String ip = jwtUtil.getValue(token, "ip");
        String remoteAddr = request.getRemoteAddr();
        Assert.error(!ip.equals(remoteAddr), BusinessCode.INVALID_IP);


        // 从 token 中获取权限码
        Object rawPermissions = jwtUtil.getValue(token, "permissions");
        List<String> userPermissions = new ArrayList<>();
        if (rawPermissions instanceof List<?>) {
            for (Object o : (List<?>) rawPermissions) {
                userPermissions.add(o.toString());
            }
        }

        String uri = request.getRequestURI();
        String requiredPermission = URL_PERMISSION_MAP.get(uri);

        if (requiredPermission != null) {
            Assert.error(userPermissions == null || !userPermissions.contains(requiredPermission), BusinessCode.NO_PERMISSION);
        }


        //放行
        return true;
    }
}
